#include<iostream>
#include<string>
#include<cstring>
#include<sys/socket.h>
#include<netinet/in.h>
#include <arpa/inet.h>

//./Client server_ip server_port
int main(int argc,char* argv[])
{
    if(argc<3)
    {
        std::cerr<<"Usage:"<<argv[0]<<"server_ip server_port"<<std::endl;
        return 1;
    }
    std::string server_ip=argv[1];
    uint16_t server_port=std::stoi(argv[2]);

    //创建套接字：
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket fail!"<<std::endl;
        return 2;
    }
    //由服务器给客户端随机分配端口
    //首次发送消息的时候，OS会自动给Clientbind
    //客户端的端口是几不重要，唯一确定的就可以
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(server_port);
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());
    while(1)
    {
        std::string input;
        std::cout<<"Please Enter:";
        std::getline(std::cin,input);
        //向服务器发送数据
        ssize_t ret=sendto(sockfd,input.c_str(),sizeof(input),0,(struct sockaddr*)&server,sizeof(server));
        (void)ret;

        //接受服务器发来的数据
       char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        memset(&buffer,0,sizeof(buffer));
        ssize_t n=recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
}
